import util from '../utils/util'
const app = getApp()
let getBills = (ctx, cb) => {

  let tableId = getApp().globalData.tableId,
    Bills = new wx.BaaS.TableObject(tableId),
    query1 = new wx.BaaS.Query(),
    query2 = new wx.BaaS.Query(),
    openid = app.globalData.openid,
    date = util.formatTime(new Date).substring(0, 7)

  query1.contains('openid', openid)
  query2.contains('billDate', date)

  let query = wx.BaaS.Query.and(query1, query2)

  Bills.setQuery(query).orderBy('-billDate').find()
    .then(res => cb(res))
    .catch(err => console.dir(err))
}

let addBill = (ctx, cb) => {

  let openid = app.globalData.openid

  let tableId = getApp().globalData.tableId,
    Bills = new wx.BaaS.TableObject(tableId),
    Bill = Bills.create(),
    billCate = ctx.data.cate,
    billName = '',
    billMoney = '',
    billDate = '',
    billRemark = ''


  if (billCate == '-') {
    billName = ctx.data.firstType_expense,
      billMoney = ctx.data.money_expense,
      billDate = ctx.data.selectdate_expense,
      billRemark = ctx.data.remarks_expense
  } else if (billCate == '+') {
    billName = ctx.data.firstType_income,
      billMoney = ctx.data.money_income,
      billDate = ctx.data.selectdate_income,
      billRemark = ctx.data.remarks_income
  }

  let data = {
    openid,
    billCate,
    billName,
    billMoney,
    billDate,
    billRemark,
  }

  Bill.set(data)
    .save()
    .then(res => cb(res))
    .catch(err => console.dir(err))

}

let updateBill = (ctx, cb) => {
  let tableId = getApp().globalData.tableId,
    recordId = ctx.data.id,
    billCate = ctx.data.cate,
    billName = ctx.data.Type,
    billMoney = ctx.data.money,
    billDate = ctx.data.date,
    billRemark = ctx.data.remarks


  let Bills = new wx.BaaS.TableObject(tableId),
    Bill = Bills.getWithoutData(recordId)

  let data = {
    billCate,
    billName,
    billMoney,
    billDate,
    billRemark,
  }

  Bill.set(data)
    .update()
    .then(res => cb(res))
    .catch(err => console.dir(err))
}

let deleteBill = (ctx, cb) => {
  let tableId = getApp().globalData.tableId,
    recordId = ctx.data.id

  let Bills = new wx.BaaS.TableObject(tableId)

  Bills.delete(recordId)
    .then(res => cb(res))
    .catch(err => console.dir(err))
}

let getBill = (ctx, cb) => {
  let tableId = getApp().globalData.tableId,
    Bills = new wx.BaaS.TableObject(tableId),
    query1 = new wx.BaaS.Query(),
    openid = wx.BaaS.storage.get('openid')

  query1.contains('openid', openid)

  Bills.setQuery(query1).orderBy('billDate').find()
    .then(res => cb(res))
    .catch(err => console.dir(err))
}

module.exports = {
  getBill,
  getBills,
  addBill,
  updateBill,
  deleteBill,
}
